package com.coocaa.x.service.litecache;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.service.litecache.LiteCacheHelper.CacheRunnable;
import com.coocaa.x.service.litecache.LiteCacheHelper.LiteCacheHelperCachingListener;
import com.coocaa.x.service.litecache.LiteCacheHelper.LiteCacheTable;
import com.skyworth.framework.skysdk.util.MD5;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lu on 15-3-14.
 */
public class OnlineCacheRunnable extends CacheRunnable {
    public OnlineCacheRunnable(String url, LiteCacheHelperCachingListener listener) {
        super(url, listener);
    }

    @Override
    protected LiteCacheTable doRealCache() throws Exception {
        while (!Android.isNetConnected(CoocaaApplication.getContext())) {
            Thread.sleep(200);
        }
        String save_path = LiteCacheHelperConfig.getImageCacheDir() + MD5.md5s(url);// System.currentTimeMillis();
        RandomAccessFile oSavedFile = null;
        HttpURLConnection httpUrl = null;
        InputStream input = null;
        try {
            URL _url = new URL(url);
            oSavedFile = new RandomAccessFile(save_path, "rw");
            httpUrl = (HttpURLConnection) _url.openConnection();
            input = httpUrl.getInputStream();
            byte[] b = new byte[1024];
            int nRead;
            while ((nRead = input.read(b)) > 0)
                oSavedFile.write(b, 0, nRead);
            LiteCacheTable mydata = new LiteCacheTable();
            mydata.cache_url = save_path;
            mydata.url = url;
            mydata.recent_used = System.currentTimeMillis();
            return mydata;
        } catch (Exception e) {
            throw e;
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (oSavedFile != null)
                try {
                    oSavedFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (httpUrl != null)
                httpUrl.disconnect();
        }
    }
}
